import { http } from "../../utils"
import { Table, Popconfirm, Button, message, Tag } from 'antd'
import React, { useEffect, useState } from 'react'
import '../questionLibrary/question.scss'
import NewQuestionComponent from "../../component/newQuestionComponent"
function Question () {
  const [loading, setLoading] = useState(false)
  const [current, setCurrent] = useState(1)
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  })
  const onChange = (pagination, filters, sorter,) => {
    // console.log('params', pagination, filters, sorter)
    setCurrent(pagination.current)
    setTableParams({
      pagination,
      filters,
      ...sorter,
    })
  }
  const [questionList, setQuestionList] = useState([{
    "id": 24,
    "question": {
      "answer": true,
      "description": null,
      "score": 5,
      "question_number": null,
      "question_stem": "1+1=2"
    },
    "description": "这可是小学数学题啊",
    "subject_name": "小学数学",
    "type_name": "判断题",
    "complexity_name": "困难",
    "create_by": 1,
    "create_time": "2022-09-04 10:56:10"
  }
  ])
  const handleDelete = (id) => { //删除题目
    const newData = questionList.filter((item) => item.id !== id)
    setQuestionList(newData)
  }

  const loadQuestionList = async () => {
    const res = await http.get(`/base_server/api/v1/pub/question/find_by_page${'?current='}${current}`)
    setQuestionList(res.data.records)
    setLoading(false)
    setTableParams({
      ...tableParams,
      pagination: {
        ...tableParams.pagination,
        total: 400, // 200 is mock data, you should read it from server
        // total: data.totalCount,
      },
    })
  }
  useEffect(() => {
    loadQuestionList()
  }, [current])// eslint-disable-line

  const columns = [
    {
      title: '题目编号',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: '难易度',
      dataIndex: 'complexity_name',
      filters: [
        {
          text: '简单',
          value: '简单',
        },
        {
          text: '入门',
          value: '入门',
        }, {
          text: '中等',
          value: '中等',
        }, {
          text: '进阶',
          value: '进阶',
        }, {
          text: '困难',
          value: '困难',
        },
      ],
      onFilter: (value, record) => record.complexity_name.indexOf(value) === 0,
      sortDirections: ['descend'],
      render: function (text, record, index) { //参数分别为当前行的值，当前行数据，行索引
        if (text === '简单') {
          return (<Tag color="#00f5d4">简单</Tag>)
        }
        if (text === '入门') {
          return (<Tag color="#b9fbc0">入门</Tag>)
        }
        if (text === '中等') {
          return (<Tag color="#e7c6ff">中等</Tag>)
        }
        if (text === '困难') {
          return (<Tag color="#f94144">困难</Tag>)
        }
        if (text === '进阶') {
          return (<Tag color="#ff5400">进阶</Tag>)
        }
      }
    },
    {
      title: '题目',
      dataIndex: ['question', 'question_stem'],
    },
    {
      title: '答案',
      dataIndex: ['question', 'answer'],
      render: function (text, record, index) { //参数分别为当前行的值，当前行数据，行索引
        if (record.type_name === '判断题') {

          return (<div>

            {record.question.answer === true ? '正确' : '错误'}
          </div>)
        } if (record.type_name === '单选题') {
          return (
            <div>
              {record.question.answer.includes(0) ? 'A' : ''}
              {record.question.answer.includes(1) ? 'B' : ''}
              {record.question.answer.includes(2) ? 'C' : ''}
              {record.question.answer.includes(3) ? 'D' : ''} </div>
          )
        } if (record.type_name === '多选题') {
          return (
            <div>
              {record.question.answer.includes(0) ? 'A' : ''}
              {record.question.answer.includes(1) ? 'B' : ''}
              {record.question.answer.includes(2) ? 'C' : ''}
              {record.question.answer.includes(3) ? 'D' : ''} </div>
          )
        }
        else {
          return (<div>{text}</div>)
        }
        // return (
        //   <div>{index}</div>
        // )
      }

    },
    {
      title: '分值',
      dataIndex: ['question', 'score'],
      sorter: (a, b) => a.question.score - b.question.score,
    },
    {
      title: '所属学科',
      dataIndex: 'subject_name',

    },
    {

      title: '题目类型',
      dataIndex: 'type_name',
      filters: [
        {
          text: '判断题',
          value: '判断题',
        },
        {
          text: '填空题',
          value: '填空题',
        },
        {
          text: '单选题',
          value: '单选题',
        }, {
          text: '多选题',
          value: '多选题',
        }, {
          text: '简答题',
          value: '简答题',
        },
      ],
      onFilter: (value, record) => record.type_name.indexOf(value) === 0,
      sortDirections: ['descend'],
      render: function (text, record, index) { //参数分别为当前行的值，当前行数据，行索引
        if (text === '判断题') {
          return (<Tag color="#bde0fe">判断题</Tag>)
        }
        if (text === '填空题') {
          return (<Tag color="#d6ccc2">填空题</Tag>)
        }
        if (text === '单选题') {
          return (<Tag color="#ffb703">单选题</Tag>)
        }
        if (text === '多选题') {
          return (<Tag color="#0096c7">多选题</Tag>)
        }
        if (text === '简答题') {
          return (<Tag color="#ff5400">简答题</Tag>)
        }
      }
    }, {
      title: '题目说明',
      dataIndex: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
    },
    {
      title: 'operation',
      dataIndex: 'operation',
      render: (_, record) =>
        questionList.length >= 1 ? (
          <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record.id)}>
            <Button>Delete</Button>
          </Popconfirm>
        ) : null,
    },
  ]
  //填空的hook干脆直接在这接收答案
  const [fillAnswer, setFillAnswer] = useState([{ id: 0, myanswer: '' }])
  //单选
  const [select, setSelect] = useState([{ id: 0, name: '选项A:', answer: '' },
  { id: 1, name: '选项B:', answer: '' },
  { id: 2, name: '选项C:', answer: '' },
  { id: 3, name: '选项D:', answer: '' },])
  //
  //多选
  const [selectItem, setSelectItem] = useState([])

  function delHtmlTag (content) {

    return content.replace(/<[^>]+>/g, "")//去掉所有的html标记
  }
  //
  //弹窗
  const [open, setOpen] = useState(false)
  const onCreate = async (values) => {
    console.log('Received values of form: ', values)
    //简答
    if (values.questionType === 5) {

      let stem = delHtmlTag(values.question_stem)
      let de = delHtmlTag(values.question_description)
      let shortAnswer = delHtmlTag(values.shortAnswer)
      try {
        await shortAdd({
          answer: shortAnswer,
          complexity: values.complexity,
          description: values.description,
          question_description: de,
          question_stem: stem,
          score: Number(values.score),
          subject_id: values.subjectType,
          type: values.questionType
        })

      } catch (e) {
        message.error(e.response?.data?.message || '添加简答题失败')
      }
    }
    //多选题
    if (values.questionType === 4) {
      const newSelectstem = select.map(function (item) {
        return item.name + item.answer
      })
      let stem = delHtmlTag(values.question_stem)
      let de = delHtmlTag(values.question_description)
      console.log(newSelectstem)
      try {
        await selectAdd({
          answer: selectItem,
          complexity: values.complexity,
          description: values.description,
          item: newSelectstem,
          question_description: de,
          question_stem: stem,
          score: Number(values.score),
          subject_id: values.subjectType,
          type: values.questionType
        })

      } catch (e) {
        message.error(e.response?.data?.message || '添加多选题失败')
      }
    }
    //单选
    if (values.questionType === 3) {
      const newSelectstem = select.map(function (item) {
        return item.name + item.answer
      })
      let stem = delHtmlTag(values.question_stem)
      let de = delHtmlTag(values.question_description)
      let arr = []
      arr.push(values.rightAnswer)
      try {
        await selectAdd({
          answer: arr,
          complexity: values.complexity,
          description: values.description,
          item: newSelectstem,
          question_description: de,
          question_stem: stem,
          score: Number(values.score),
          subject_id: values.subjectType,
          type: values.questionType
        })

      } catch (e) {
        message.error(e.response?.data?.message || '添加单选题失败')
      }
    }

    if (values.questionType === 2) {
      const newFillAnswer = fillAnswer.map(function (item, index) { //把填空题答案提取出来
        return item.myanswer
      })
      var fillSet = new Set(newFillAnswer)
      let stem = delHtmlTag(values.question_stem)
      let de = delHtmlTag(values.question_description)
      console.log(fillAnswer)
      console.log(newFillAnswer)
      console.log(fillSet)
      try {
        await gapFillAdd({
          answer: newFillAnswer,
          complexity: values.complexity,
          description: values.description,
          question_description: de,
          question_stem: stem,
          score: Number(values.score),
          subject_id: values.subjectType,
          type: values.questionType
        })

      } catch (e) {
        message.error(e.response?.data?.message || '添加填空题失败')
      }
    }
    //判断
    if (values.questionType === 1) {
      let stem = delHtmlTag(values.question_stem)
      let de = delHtmlTag(values.question_description)
      try {
        await judgeAdd({
          complexity: values.complexity,
          description: values.description,
          question_description: de,
          question_stem: stem,
          score: Number(values.score),
          subject_id: values.subjectType,
          type: values.questionType,
          answer: values.answer
        })
      } catch (e) {
        message.error(e.response?.data?.message || '添加判断题失败')
      }

    }
    setOpen(false)
  }

  async function judgeAdd ({ complexity, description, question_description, question_stem, score, subject_id, type, answer }) {
    await http.post('/base_server/api/v1/pub/question/add/judge', {
      complexity, description, question_description, question_stem, score, subject_id, type, answer
    })
  }
  async function gapFillAdd ({ answer, complexity, description, question_description, question_stem, score, subject_id, type }) {
    await http.post('/base_server/api/v1/pub/question/add/gap_filling', {
      answer, complexity, description, question_description, question_stem, score, subject_id, type
    })
  }
  async function selectAdd ({ answer, complexity, description, item, question_description, question_stem, score, subject_id, type }) {
    await http.post('/base_server/api/v1/pub/question/add/select', {
      answer, complexity, description, item, question_description, question_stem, score, subject_id, type
    })
  }
  async function shortAdd ({ complexity, description, question_description, question_stem, score, subject_id, type, answer }) {
    await http.post('/base_server/api/v1/pub/question/add/short_answer', {
      complexity, description, question_description, question_stem, score, subject_id, type, answer
    })
  }
  return (
    <div className="question-sty">
      <Button
        type="primary"
        onClick={() => {
          setOpen(true)
        }}
      >
        新建题目
      </Button>
      <NewQuestionComponent
        open={open}
        onCreate={onCreate}
        fillAnswer={fillAnswer}
        setFillAnswer={setFillAnswer}
        select={select}
        setSelect={setSelect}
        selectItem={selectItem}
        setSelectItem={setSelectItem}
        onCancel={() => {
          setOpen(false)
        }}

      />
      <Table columns={columns}
        dataSource={questionList}
        onChange={onChange}
        rowKey={(questionList) => questionList.id}
        scroll={{
          x: 1300,
        }}
        pagination={tableParams.pagination}
        loading={loading}
        size='small'
      />
    </div>
  )
};
export default Question